package com.bdqn.zhang.dao.impl.dbutil;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DButil {
    static String dirver = "";
    static String url = "";
    static String user = "";
    static String password = "";

    static {
        InputStream is = DButil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        //加载驱动
        try {
            properties.load(is);
            dirver = properties.getProperty("dirver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //加载驱动
        try {
            Class.forName(dirver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    //获取数据库链接对象
    //return返回链接对象
    //return的全局变量没有参数也行
    public static Connection getConnerction() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    public static void close(Connection conn, PreparedStatement ment, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (conn != null) {
                ment.close();
            }
            if (ment != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //增删改
    public int executeUpdate(String sql, Object[] obj) {
        PreparedStatement preparedStatement = null;
        Connection connerction = getConnerction();
        try {
            preparedStatement = connerction.prepareStatement(sql);
            if (obj != null) {
                for (int i = 0; i < obj.length; i++) {
                    preparedStatement.setObject(i + 1, obj[i]);
                }
            }
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close(connerction, preparedStatement, null);
        }
    }
}
